import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {SocketService} from "../services/socket.service";
import {ExtendHttpService} from "../../common/extend-http.service";

@Injectable()
export class MainGuard implements CanActivate {
  sessionId = null;
  constructor(
    private socketService: SocketService,
    private extendHttp: ExtendHttpService,
    private router: Router
  ) {
  }

  canActivate(next: ActivatedRouteSnapshot,
              state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    let loginInfo = JSON.parse(localStorage.getItem('loginInfo'));
    if (this.socketService.ws) {
      this.socketService.wsClose();
    }
    this.socketService.wsConnect(loginInfo.login_account, loginInfo.login_pwd, loginInfo.merchant_id)
      .subscribe(
        data => {
          this.socketService.wsMsg(data);
        },
        error => {
          console.log("socket没有连接成功")
          console.log(error)
        },
        () => {
          console.log('webSocket服务连接已经断开')
        }
      );

    // 每隔10分钟请求一次用户信息接口，保持登录
    this.extendHttp.post('/merchantApp/basics/loginInfo/getInfo', {}).subscribe(response => {
      let data = response.json();
      if (data.code == '0') {
        sessionStorage.setItem('userInfo', data['merchant']);
      } else if (data.code == '-2001') {
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 2000);
      } else {
      }
    }, error => {
    });
    if (!this.sessionId) {
      this.sessionId = setInterval(()=>{
        this.extendHttp.post('/merchantApp/basics/loginInfo/getInfo', {}).subscribe(response => {
          let data = response.json();
          if (data.code == '0') {
          } else if (data.code == '-2001') {
            setTimeout(() => {
              this.router.navigate(['/login']);
            }, 2000);
          } else {
          }
        }, error => {
        });
      }, 3600000);
    }

    return true;
  }
}
